package com.cn.common;

import com.cn.util.FastJsonUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 存储broker节点信息
 */
public class BrokerCluster {

    private static ConcurrentMap<String, Set<BrokerEntity>> broker_cluster = new ConcurrentHashMap<>();

    public static void put(String cluster, BrokerEntity broker) {
        if (StringUtils.isEmpty(cluster)) return;
        Set<BrokerEntity> list = get(cluster);
        if (list == null) {
            list = new HashSet<>();
        } else {
            for (BrokerEntity b : list) {
                if (b.getName().equals(broker.getName())) {
                    b.setAddress(broker.getAddress());
                }
            }
        }
        list.add(broker);
        broker_cluster.put(cluster, list);
    }

    public static void putAll(String cluster, BrokerEntity entity) {
        if (broker_cluster.get(cluster) != null) {
            broker_cluster.get(cluster).add(entity);
        } else {
            Set<BrokerEntity> set = new HashSet<>();
            set.add(entity);
            broker_cluster.put(cluster, set);
        }
    }

    public static void putAll1(String cluster, String result) {
        List<BrokerEntity> list = null;
        if (StringUtils.isNotEmpty(result)) {
            list = str2List(result);
        } else {
            return;
        }
        if (list == null || list.size() == 0) {
            return;
        }
        if (StringUtils.isEmpty(cluster)) {
            cluster = list.get(0).getCluster_name();
        }
        for (BrokerEntity entity : list) {
            putAll(cluster, entity);
        }
    }

    public static void del(BrokerEntity broker) {
        if (broker == null) return;
        Set<BrokerEntity> list = get(broker.getCluster_name());
        list.remove(broker);
        broker_cluster.put(broker.getCluster_name(), list);
    }

    public static Set<BrokerEntity> get(String cluster) {
        return broker_cluster.get(cluster);
    }


    public static String getCluster(String cluster) {
        return FastJsonUtil.obj2Jsonstr(get(cluster));
    }

    public static List<BrokerEntity> str2List(String result) {
        return FastJsonUtil.str2List(result, BrokerEntity.class);
    }

    public static void main(String[] args) {

    }

}
